<?php

/**
 * 中介模式：比如通话，在通话人之间有一个网络提供商，就相当于一个调制解调器。
 * 中介模式定义了一个对象，该对象封装了一组对象如何交互。被认为是一种行为模式，因为它可以改变程序的运行行为。
 * Class Mediator
 */

interface ChatRoomMediator
{
    public function showMessage(User $user, string $message);
}

//Mediator
class ChatRoom implements ChatRoomMediator
{
    public function showMessage(User $user, string $message)
    {
        $time = date('Y d, y H:i');
        $sender = $user->getName();
        echo $time . ' [' . $sender . ']: ' . $message . "\n";
    }
}

// relate object

class User
{
    protected $name;
    protected $chatMediator;

    public function __construct(string $name, ChatRoomMediator $chatMediator)
    {
        $this->name = $name;
        $this->chatMediator = $chatMediator;
    }

    public function getName()
    {
        return $this->name;
    }

    public function send($message)
    {
        $this->chatMediator->showMessage($this, $message);
    }
}

// usage
$mediator = new ChatRoom();

$john = new User('John Doe', $mediator);
$jane = new User('Jane Doe', $mediator);

$john->send('Hi there!');
$jane->send('Hey');